import { defineStore } from 'pinia'
import { loginAPI, getUserInfo, logoutAPI } from '@/api/user/index'
import type { loginType, userInfoType } from '@/api/user/type'
import { ElNotification } from 'element-plus'
import { UserStoreType } from './type'
import hour from '@/utils/time'
import { asnycRoute, constantRouter } from '@/router/routes'
import router from '@/router/index'

export const USERSTORE = defineStore({
  id: 'userinfo',
  state: (): UserStoreType => ({
    token: '',
    checkUser: null,
    userRoutes: constantRouter,
  }),
  getters: {},
  actions: {
    async LOGIN(formData: loginType) {
      const { code, data, message } = await loginAPI(formData)
      if (code === 200) {
        // 获取信息成功
        this.token = data as string
        ElNotification({
          title: hour,
          message: '欢迎回来',
          type: 'success',
        })
        return Promise.resolve()
      } else {
        ElNotification({
          title: 'Error',
          message: message,
          type: 'error',
        })
        return Promise.reject(new Error())
      }
    },
    async GETUSERINFO() {
      const { code, data, message } = await getUserInfo()
      if (code === 200) {
        this.checkUser = data as userInfoType
        // 生成路由
        const routes = data?.routes
        routes?.forEach((routeName) => {
          const result = asnycRoute.filter(
            (item) =>
              item.name === routeName[0].toUpperCase() + routeName.slice(1),
          )
          this.userRoutes.push(...result)
          result.forEach((v) => {
            router.addRoute(v)
          })
        })
        return Promise.resolve()
      } else {
        ElNotification({
          title: 'Error',
          message: message,
          type: 'error',
        })
        return Promise.reject(new Error())
      }
    },
    async LOGOUT() {
      // 判断接口的成功与否
      const { code, message } = await logoutAPI()
      if (code === 200) {
        this.token = ''
        this.checkUser = null
        this.userRoutes = []
        return Promise.resolve()
      } else {
        ElNotification({
          title: 'Error',
          message: message,
          type: 'error',
        })
        return Promise.reject(new Error())
      }
    },
  },
  persist: {
    // 修改存储中使用的键名称，默认为当前 Store的 id
    // key: 'storekey',
    // 修改为 sessionStorage，默认为 localStorage
    // storage: window.sessionStorage,
    // 部分持久化状态的点符号路径数组，[]意味着没有状态被持久化(默认为undefined，持久化整个状态)
    paths: ['token'],
  },
})
